<template>
  <div id="app">
    <div>
      <select name="" v-model="id">
        <option value="-1" disabled>请选择商品</option>
        <option v-for="(goods,idx) in list" :key="idx" :value="idx" v-text="goods.name"></option>
      </select>
      <button class="goods-btn" @click="changeCount(-1)">-</button>
      <input type="text" v-model="count" class="goods-count">
      <button class="goods-btn" @click="changeCount(1)">+</button>
    </div>
    <h3>商品清单：</h3>
    <table cellspacing="0">
      <tr>
        <th>序号</th>
        <th>商品名称</th>
        <th>单位</th>
        <th>数量</th>
        <th>金额</th>
      </tr>
      <tr v-for="(goods,idx) in list" :key="idx">
        <td v-text="idx + 1"></td>
        <td v-text="goods.name"></td>
        <td v-text="'￥' + goods.price"></td>
        <td v-text="goods.count"></td>
        <td v-text="goods.amount"></td>
      </tr>
      <tr>
        <td>总价：</td>
        <td colspan="4">{{totalPrice}}</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data:function(){
    return {
      list:[
        {name:"香蕉",price:3.14,count:0,amount:0},
        {name:"苹果",price:2.25,count:0,amount:0},
        {name:"鸭梨",price:6,count:0,amount:0}
      ],
      id:-1,
      count:0
    }
  },
  methods:{
    changeCount(num){
      var id = this.id;
      if(id < 0) return;
      var sum = this.list[id]['count'] + num;
      if(sum < 0){
        sum = 0;
      }
      this.list[id]['count'] = sum;
      this.count = sum;
      this.list[id]['amount'] = this.list[id]['price'] * sum;
    },
  },
  computed:{
    totalPrice(){
      var total = 0;
      for(var item in this.list){
        total += this.list[item]['amount'];
      }
      return total;
    }
  },
  watch:{
    'id':{
      handler(newVal,oldVal){
        if(newVal >= 0 && newVal != oldVal){
          this.count = this.list[this.id]['count'];
        }
      },
      deep:true
    }
  }
}
</script>

<style>
  table{
    border:1px solid #666;
  }
  td,th{
    border-style:solid;
    border-width:0 0 1px 1px;
    border-color:#666;
  }
</style>
